package com.changgou.order.controller;

import com.changgou.order.pojo.OrderItem;
import com.changgou.order.service.CartService;
import com.changgou.util.Result;
import com.changgou.util.StatusCode;
import com.changgou.util.TokenDecode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/*****
 * @Author: 黑马训练营
 * @Description: com.changgou.order.controller
 ****/
@RestController
@RequestMapping(value = "/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /****
     * 加载用户选中需要下单的商品
     * /choose/list
     */
    @RequestMapping(value = "/choose/list")
    public Result<List<OrderItem>> list(@RequestParam(value = "ids") List<String> ids){
        //获取用户名
        String username = TokenDecode.getUserInfo().get("username");

        //调用Service查询指定商品的购物车明细集合
        List<OrderItem> items = cartService.list(ids,username);
        return new Result<List<OrderItem>>(true,StatusCode.OK,"查询清单列表成功！",items);
    }

    /***
     * 购物车列表查询
     */
    @GetMapping(value = "/list")
    public Result<List<OrderItem>> list(){
        //SpringSecurity可以获取用户的信息
        //Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Map<String, String> userInfo = TokenDecode.getUserInfo();

        String username = userInfo.get("username");
        //调用Service查询购物车列表
        List<OrderItem> list = cartService.list(username);
        return new Result<List<OrderItem>>(true,StatusCode.OK,"购物车列表查询成功！",list);
    }

    /***
     * 添加购物车
     */
    @GetMapping(value = "/add")
    public Result add(Integer num, String id){
        Map<String, String> userInfo = TokenDecode.getUserInfo();
        String username = userInfo.get("username");

        //添加购物车
        cartService.add(num,id,username);
        return new Result(true, StatusCode.OK,"添加购物车成功！");
    }
}
